<?php

namespace App\Api\Fibrpro;

use PhalApi\Api;
use App\Domain\User\User as UserDomain;
use PhalApi\Exception\BadRequestException;
use PhpOffice\PhpWord\TemplateProcessor;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

use Qiniu\Auth;


/**
 * fibrpro报价发票和收据,运送单
 *   @desc 报价单
 */
class Invoice extends Api
{

    public function getRules()
    {
        return array(
            'po' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => 'id'),
            ),
            'getInvoiced' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'desc' => 'id'),
            ),
        );
    }


    /**
     * 通过id生成getInvoiced
     * @desc 订单word
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function getInvoiced()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        //Application
        $id = $this->id;
        $Application = 1;
        $previousinvoiced = 0;
        $received = 0;

        $Invioced = \PhalApi\DI()->notorm
            ->fibrpro_price_transport
            ->where('price_id', $id)
            ->where('state', 1)
            ->order("id DESC")
            ->fetchAll();


        if( $Invioced ){
            $Application = count($Invioced) + 1;
            $data_json = json_decode($Invioced[count($Invioced)-1]['data_json'], true);
            $previousinvoiced = $data_json['amount'];
            $received = $data_json['previousinvoiced_amount'];
        }
        
        // 对$Invioced数组按照id从小到大排序
        usort($Invioced, function($a, $b) {
            return $a['id'] - $b['id'];
        });

        $Res = array(
            "price_id" => $id,
            "Application" => $Application,
            "previousinvoiced" => $previousinvoiced,
            "received" => $received,
            "P" => array_map(function($item){
                return json_decode($item['data_json'], true);
            }, $Invioced),
        );

        return $Res;
    }



    /**
     * 通过id生成po
     * @desc 订单word
     * @return array data 签名url
     * @exception 400 非法请求，参数传递错误
     */
    public function po()
    {
        // 最简单的处理方式
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *');

        $id = $this->id;   // 账号参数

        $Invioce = \PhalApi\DI()->notorm
            ->fibrpro_price_transport
            ->where('id', $id)
            ->fetchOne();

        $Price = \PhalApi\DI()->notorm
            ->fibrpro_price
            ->where('id', $Invioce['price_id'])
            ->fetchOne();

        $price_form = json_decode($Price['form_json'], true);

        if ($Invioce) {
            $form = json_decode($Invioce['data_json'], true);
        }

        // 将$price_form和$form数组合并
        // 如果$form存在，则使用array_merge合并两个数组
        // $form的键值会覆盖$price_form中相同的键值
        if ($form) {
            $form = array_merge($price_form, $form);
        } else {
            $form = $price_form;
        }

        // if( $form['Drafting'] && $form['Drafting'][0]  == "AL"){
        //     $form['Drafting_'] == "Anson Lee";
        // }else{
        //     $form['Drafting_'] == "Stacey Chan";
        // }


        // return $form;
        if( $Invioce['types'] == '訂單發票' ){
            $word = new TemplateProcessor('templates/INVOICE_FIBRPRO.docx');
        }else if( $form['types'] == 'CITF' ){
            $word = new TemplateProcessor('templates/Quotation_FIBRPRO.docx');
        }

        if( $form['companyfax_']){
            // 使用正则表达式去除字符串中的/n，并替换为换行符
            $form['companyfax_'] = preg_replace('/\/n/', "\n", $form['companyfax_']);
        }

        if ($form['sexP']) {
            $form['sexTtitle'] = $form['sexP'];
            $form['sex'] = $form['sexP'];
        }

        // if( $form['formTotal']['amountdiscount'] > 0 ){
        //     $form['amountdiscount_'] = '-' . number_format($form['formTotal']['amountdiscount'], 2, '.', ',');
        // }else{
        //     $word->deleteRow('amountdiscount_', array($form['formTotal']['amountdiscount'])); // 删除行
        // }

        if($form['formTotal']['amount']){
            $form['amount_'] = number_format($form['formTotal']['amount'], 2, '.', ',');
        }



        if (is_array($form['who']) && count($form['who']) > 1) {
            $form['whoPrint'] = 'Elvin Tang';
            $form['whoTitle'] = 'Marketing Manager';
        } elseif (is_array($form['who']) && in_array('ET', $form['who'])) {
            $form['whoPrint'] = 'Elvin Tang';
            $form['whoTitle'] = 'Marketing Manager';
        } elseif (is_array($form['who']) && in_array('TW', $form['who'])) {
            $form['whoPrint'] = 'Director. Tin Wong';
            $form['whoTitle'] = 'Engineering Manager';
        }

        if ($form['formDelivery']['deliverytripQTY'] > 0) {
            $num = $form['formDelivery']['deliverytripQTY'];
            $numWords = [
                1 => 'ONE',
                2 => 'TWO',
                3 => 'THREE',
                4 => 'FOUR',
                5 => 'FIVE',
                6 => 'SIX',
                7 => 'SEVEN',
                8 => 'EIGHT',
                9 => 'NINE',
                10 => 'TEN'
            ];
            $englishNum = isset($numWords[$num]) ? $numWords[$num] : $num;
            $form['Delivery_'] = $englishNum . ($num > 1 ? ' lots' : ' lot');
        }

        if ($form['formDelivery']['Validity']) {
            $form['Validity'] = $form['formDelivery']['Validity'];
        }
        if (isset($form['formTotal']['deposit'])) {
            $form['rate'] = $form['formTotal']['deposit'];
            $form['rate_'] = 100 - $form['rate'];
        }

        $form['outstanding'] = $form['formTotal']['amount'] - $form['previousinvoiced_amount'];
        if( $form['received'] ){
            $form['received_'] = number_format($form['received'], 2, '.', ',');
        }else{
            $form['received_'] = '0';
        }

        if( $form['amount'] ){
            $form['v_amount'] = number_format($form['amount'], 2, '.', ',');
        }
        
        if( $form['previousinvoiced'] ){
            $form['previousinvoiced_'] = number_format($form['previousinvoiced'], 2, '.', ',');
        }else{
            $form['previousinvoiced_'] = '0';
        }

        if( $form['previousinvoiced_amount'] ){
            $form['previousinvoiced_amount_'] = number_format($form['previousinvoiced_amount'], 2, '.', ',');
        }else{
            $form['previousinvoiced_amount_'] = '0';
        }

        if( $form['outstanding'] ){
            $form['outstanding_'] = number_format($form['outstanding'], 2, '.', ',');
        }else{
            $form['outstanding_'] = '0';
        }

        if($form['paymenttype'] == 'percentage'){
            $form['P_show_text'] = $form['perc']. "% Deposit";
        }

        if($form['paymenttype'] == 'unusual'){
            $showArr = [];
            foreach ($form['unusual'] as $item) {
                $showArr[] = 'Item ' . $item['index'] . ' (' . $item['selectedQty'] . 'pcs)';
            }
            $form['P_show_text'] = implode(' , ', $showArr) .' '. $form['balance'] . '% Bal Total';
        }



        //批量自动填
        foreach ($form as $key => $value) {
            if (strpos($value, 'http') === false) {
                if ($value) {
                    $word->setValue($key, $value);
                } else {
                    $word->setValue($key, ''); // 替换文本内容
                }
            }
        }

        if ($form['title'] == 'Synthetec® Stone Grating') {
            $word->setValue('r_', '®');
            $word->setValue('title_', 'Synthetec');
        } else {
            $word->setValue('r_', "");
            $word->setValue('title_', "Synthetic");
        }

        $old_ip = array();
        if($form['P']){
            $iplist = array();
            foreach($form['P'] as $key => $value ){
                $iplist['IP_index'] = $value['Application'];
                if( $value['paymenttype'] == 'percentage'){
                    $iplist['IP_content'] = $value['perc']. "% Deposit";
                }
                if($value['paymenttype'] == 'unusual'){
                    $showArr = [];
                    foreach ($form['unusual'] as $item) {
                        $showArr[] = 'Item ' . $item['index'] . ' (' . $item['selectedQty'] . 'pcs)';
                    }
                    $iplist['IP_content'] = implode(' , ', $showArr)  .' '. $value['balance'] . 
            $form['P_show_text'] = implode(' , ', $showArr) .' '. $form['balance'] . '% Bal Total';
                }
                $iplist['ip_amount'] = number_format($value['amount'], 2, '.', ',');
                $old_ip[] = $iplist;
            }

            // return $old_ip;
            $word->cloneRowAndSetValues('IP_index', $old_ip);
        }else{
            $word->deleteRow('IP_index'); // 删除行
        }

        

        $products = $form['SelectedProducts'];
        // 遍历 SelectedProducts 数组
        foreach ($form['SelectedProducts'] as $key => $product) {
            // 单独检查 moldtotal 是否为空
            if (!($product['total'])) {
                // 如果为空，则赋值为 "RATE ONLY"
                $form['SelectedProducts'][$key]['total_'] = "RATE ONLY";
            }
            // 单独检查 quality 是否为空
            if (empty($product['quality']) || $product['quality'] === '0') {
                $form['SelectedProducts'][$key]['quality_'] = "RATE ONLY";
            }
            if( $product['level'] == "Other" ){
                $form['SelectedProducts'][$key]['level'] = $product['level_Other'];
            }
        }
        // 产品
        $word->cloneRowAndSetValues('productIndex', $form['SelectedProducts']);


        // return array($form['formMold']);
        if ($form['formMold'] && $form['formMold']['moldcharge']) {
            $form['formMold']['moldQTY'] =  $form['formMold']['moldQTY'] ?  $form['formMold']['moldQTY'] : 'RATE ONLY';
            $form['formMold']['moldtotal_'] =  $form['formMold']['moldtotal'] ?  $form['formMold']['moldtotal_'] : 'RATE ONLY';
            $word->cloneRowAndSetValues('moldindex', array($form['formMold']));
        } else {
            $word->deleteRow('moldindex'); // 删除行
        }
        // 设计
        if ($form['formColor'] && $form['formColor']['colorcharge']) {

            $form['formColor']['colorunitrate_'] = number_format($form['formColor']['colorunitrate'], 2, '.', ','); // 保留两位小数，四舍五入
            $form['formColor']['colortotal_'] = number_format($form['formColor']['colortotal'], 2, '.', ','); // 保留两位小数，四舍五入

            $form['formColor']['colorQTY'] =  $form['formColor']['colorQTY'] ?  $form['formColor']['colorQTY'] : 'RATE ONLY';
            $form['formColor']['colorunitrate_'] =  $form['formColor']['colorunitrate_'] ?  $form['formColor']['colorunitrate_'] : 'RATE ONLY';
            $form['formColor']['colortotal_'] =  $form['formColor']['colortotal'] ?  $form['formColor']['colortotal_'] : 'RATE ONLY';
            
            $word->cloneRowAndSetValues('colorindex', array($form['formColor']));
        } else {
            $word->deleteRow('colorindex'); // 删除行
        }

        // 运输
        $form['formDelivery']['deliverytripprice_'] = number_format($form['formDelivery']['deliverytripprice'], 2, '.', ',');
        $form['formDelivery']['deliverytotal_'] = number_format($form['formDelivery']['deliverytotal'], 2, '.', ',');
        $word->cloneRowAndSetValues('deliveryindex', array($form['formDelivery']));

        
        $form['vpImg'] = "https://img.wenfree.cn/images/fibrpro/et%2Btw.png";
        $word->setImageValue('vpImg', $form['vpImg']);
        $word->setImageValue('vsign', $form['vsign']);


        $wordPath = "template/". $Invioce['name'] . "_INVIOCE.docx";
        $word->saveAs($wordPath);

        $url = "https://api.wenfree.cn/" . $wordPath;
        // return [$url, $form];
        return array(
            "url" => $url, 
            "msg" => "done", 
            "form" => $form,
        ); //返回word路径，前端下载
    }


}
